<template>
    <div class="order-detail-container">
        <!-- 订单状态栏 -->
        <el-card class="status-card">
            <div class="status-header">
                <span class="order-id">订单号：{{ orderData.id }}</span>
                <el-tag :type="statusTagType" effect="dark" size="medium">
                    {{ orderData.statusText }}
                </el-tag>
            </div>
            <el-steps :active="statusStep" align-center class="status-steps">
                <el-step title="下单成功" :description="orderData.createTime" />
                <el-step title="商品出库" :description="orderData.deliveryTime" />
                <el-step title="运输中" :description="orderData.shippingTime" />
                <el-step title="已签收" :description="orderData.receiveTime" />
            </el-steps>
        </el-card>

        <!-- 收货信息 -->
        <el-card class="info-card">
            <div slot="header" class="card-header">
                <i class="el-icon-location-outline"></i>
                <span>收货信息</span>
            </div>
            <div class="address-info">
                <p><span class="label">收货人：</span>{{ orderData.receiverName }}</p>
                <p><span class="label">联系电话：</span>{{ orderData.receiverPhone }}</p>
                <p><span class="label">收货地址：</span>{{ fullAddress }}</p>
            </div>
        </el-card>

        <!-- 价格明细 -->
        <el-card class="price-card">
            <div class="price-list">
                <p class="price-item">
                    <span>商品总额：</span>
                    <span>¥{{ orderData.totalAmount | priceFormat }}</span>
                </p>
                <p class="price-item">
                    <span>运费：</span>
                    <span>+ ¥{{ orderData.freight | priceFormat }}</span>
                </p>
                <p class="price-item">
                    <span>优惠券：</span>
                    <span>- ¥{{ orderData.coupon | priceFormat }}</span>
                </p>
                <el-divider />
                <p class="total-price">
                    <span>实付款：</span>
                    <span class="price">¥{{ orderData.payAmount | priceFormat }}</span>
                </p>
            </div>
        </el-card>

        <!-- 操作按钮（仅修改此处） -->
        <div class="action-buttons">
            <el-button @click="$router.back()">返回列表</el-button>
            <el-button type="danger" v-if="showCancel" @click="handleCancel">取消订单</el-button>
            <el-button type="primary" v-if="showPay">立即支付</el-button>
            <!-- 关键修复：拆分逻辑，先加载数据再打开弹窗 -->
            <el-button type="info" @click="fetchHistoryAndOpen()">查看物流详情</el-button>
            <el-button type="success" @click="handleConfirm">确认收货</el-button>
        </div>

        <!-- 订单历史弹窗（原始变量+原始绑定） -->
        <el-dialog title="订单历史详情" :visible.sync="orderHistoryDialogVisible" width="60%" class="history-dialog">
            <div v-if="historyList && historyList.length">
                <h3 class="section-title">订单变更记录（共{{ historyList.length }}次）</h3>
                <el-timeline>
                    <el-timeline-item v-for="(item, index) in historyList" :key="index"
                        :timestamp="formatTime(item.updateTime)" placement="top">
                        <el-card class="history-card">
                            <div class="info-item">
                                <label>操作类型：</label>
                                <el-tag :type="statusTag(item.status)">
                                    {{ statusText(item.status) }}
                                </el-tag>
                            </div>
                            <div class="info-item">
                                <label>操作时间：</label>
                                <span>{{ formatTime(item.updateTime) }}</span>
                            </div>
                            <div v-if="item.newMessage" class="info-item">
                                <label>备注信息：</label>
                                <div class="message-content">{{ item.newMessage }}</div>
                            </div>
                        </el-card>
                    </el-timeline-item>
                </el-timeline>
            </div>

            <el-empty v-else description="暂无历史记录"></el-empty>

            <template v-slot:footer>
                <el-button type="primary" @click="orderHistoryDialogVisible = false" size="small">
                    关闭
                </el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { getOrderById, getLogisticsInfo, getOrderDetail } from '@/api/user/order';
import { cancelOrder, confirmReceipt } from '@/api/user/order';

export default {
    filters: {
        priceFormat(value) {
            return Number(value || 0).toFixed(2);
        }
    },
    data() {
        return {
            orderData: {
                orderSn: '',
                status: 0,
                statusText: '',
                createTime: '',
                receiverName: '',
                receiverPhone: '',
                province: '',
                city: '',
                district: '',
                address: '',
                items: [],
                totalAmount: 0,
                freight: 0,
                coupon: 0,
                payAmount: 0
            },
            historyList: [],
            orderHistoryDialogVisible: false,
            logisticsDialogVisible: false,
            logisticsInfo: {
                company: '',
                number: '',
                traces: []
            }
        };
    },
    computed: {
        statusTagType() {
            const typeMap = ['info', 'primary', 'warning', 'success', 'danger'];
            return typeMap[this.orderData.status] || 'info';
        },
        statusStep() {
            return Math.min(this.orderData.status + 1, 4);
        },
        fullAddress() {
            const { province, city, district, address } = this.orderData;
            return `${province} ${city} ${district} ${address}`.trim();
        },
        showCancel() {
            return this.orderData.status <= 1;
        },
        showPay() {
            return this.orderData.status === 0;
        },
        showLogistics() {
            return this.orderData.status >= 2;
        },
        showConfirm() {
            return this.orderData.status === 2;
        }
    },
    methods: {
        async loadData() {
            try {
                const res = await getOrderById(this.$route.params.id);
                if (res?.data?.data) {
                    this.orderData = res.data.data;
                } else {
                    this.$message.error('获取订单数据失败');
                }
            } catch (error) {
                this.$message.error('加载订单详情失败');
            }
        },
        async handleCancel() {
            try {
                await this.$confirm('确定要取消该订单吗？', '提示', { type: 'warning' });
                await cancelOrder(this.orderData.id);
                this.$message.success('订单已取消');
                await this.loadData();
            } catch (error) {
                if (error !== 'cancel') {
                    this.$message.error('取消订单失败');
                }
            }
        },
        async handleConfirm() {
            try {
                await this.$confirm('请确认已收到商品', '确认收货', {
                    confirmButtonText: '确认收货',
                    cancelButtonText: '取消',
                    type: 'success'
                });
                await confirmReceipt(this.orderData.id);
                this.$message.success('收货成功');
                await this.loadData();
            } catch (error) {
                if (error !== 'cancel') {
                    this.$message.error('确认收货失败');
                }
            }
        },
        async fetchHistoryAndOpen() {
            try {
                const res = await getOrderDetail(this.$route.params.id);
                this.historyList = res?.data?.data || [];
                this.orderHistoryDialogVisible = true;
            } catch (error) {
                this.$message.error('获取历史记录失败');
            }
        },
        async fetchLogisticsInfo() {
            try {
                const res = await getOrderDetail(this.$route.params.id);
                if (res?.data?.data) {
                    this.historyList = res.data.data;
                } else {
                    this.logisticsInfo = {
                        company: '获取失败',
                        number: '获取失败',
                        traces: [{ status: '获取物流信息失败，请稍后重试' }]
                    };
                }
            } catch (error) {
                this.$message.error('获取物流信息失败');
            }
        },
        copyLogisticsNumber() {
            const input = document.createElement('input');
            input.value = this.logisticsInfo.number;
            document.body.appendChild(input);
            input.select();
            document.execCommand('copy');
            document.body.removeChild(input);
            this.$message.success('运单号已复制');
        },
        formatTime(time) {
            return time || '';
        },
        statusTag(status) {
            const typeMap = ['info', 'success', 'warning', 'danger', 'info'];
            return typeMap[status] || 'default';
        },
        statusText(status) {
            const textMap = ['待支付', '已支付', '已发货', '已完成', '已取消'];
            return textMap[status] || '未知状态';
        }
    },
    mounted() {
        this.loadData();
    }
};
</script>

<style lang="less" scoped>
.order-detail-container {
    padding: 20px;
    max-width: 1200px;
    margin: 0 auto;

    .status-card {
        margin-bottom: 20px;

        .status-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;

            .order-id {
                font-size: 16px;
                color: #666;
            }
        }

        .status-steps {
            /deep/ .el-step__head {
                &.is-process {
                    color: #409EFF;
                    border-color: #409EFF;
                }
            }
        }
    }

    .card-header {
        i {
            margin-right: 8px;
            color: #409EFF;
        }

        span {
            font-weight: bold;
        }
    }

    .address-info {
        line-height: 1.8;

        .label {
            color: #999;
            width: 80px;
            display: inline-block;
        }
    }

    .price-card {
        margin-top: 20px;
        text-align: right;

        .price-list {
            width: 300px;
            margin-left: auto;

            .price-item {
                display: flex;
                justify-content: space-between;
                margin-bottom: 10px;
                color: #666;
            }

            .total-price {
                font-size: 18px;
                color: #e4393c;
                font-weight: bold;

                .price {
                    font-size: 24px;
                }
            }
        }
    }

    .action-buttons {
        margin-top: 30px;
        text-align: center;

        button {
            margin: 0 10px;
        }
    }
}

.logistics-dialog {
    .logistics-header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 15px;

        .logistics-company,
        .logistics-number {
            display: flex;
            align-items: center;

            span {
                color: #666;
                margin-right: 5px;
            }

            strong {
                color: #333;
            }
        }
    }

    .logistics-timeline {
        max-height: 400px;
        overflow-y: auto;
        padding: 0 20px;

        /deep/ .el-timeline-item__timestamp {
            color: #999;
            font-size: 13px;
            margin-bottom: 5px;
        }
    }
}
</style>